import pytdx
import time
from pytdx.hq import TdxHq_API
from pytdx.pool.ippool import AvailableIPPool
from pytdx.config.hosts import hq_hosts
import random
import logging
import pprint
import akshare as ak
import os
from pytdx.params import TDXParams

# 行情服务器列表
Tdx_hosts = [
    ("长城国瑞电信1", "218.85.139.19", 7709),
    ("长城国瑞电信2", "218.85.139.20", 7709),
    ("长城国瑞网通", "58.23.131.163", 7709),
    ("上证云成都电信一", "218.6.170.47", 7709),
    ("上证云北京联通一", "123.125.108.14", 7709),
    ("上海电信主站Z1", "180.153.18.170", 7709),
    ("上海电信主站Z2", "180.153.18.171", 7709),
    ("上海电信主站Z80", "180.153.18.172", 80),
    ("北京联通主站Z1", "202.108.253.130", 7709),
    ("北京联通主站Z2", "202.108.253.131", 7709),
    ("北京联通主站Z80", "202.108.253.139", 80),
    ("杭州电信主站J1", "60.191.117.167", 7709),
    ("杭州电信主站J2", "115.238.56.198", 7709),
    ("杭州电信主站J3", "218.75.126.9", 7709),
    ("杭州电信主站J4", "115.238.90.165", 7709),
    ("杭州联通主站J1", "124.160.88.183", 7709),
    ("杭州联通主站J2", "60.12.136.250", 7709),
    ("杭州华数主站J1", "218.108.98.244", 7709),
    ("杭州华数主站J2", "218.108.47.69", 7709),
    ("义乌移动主站J1", "223.94.89.115", 7709),
    ("青岛联通主站W1", "218.57.11.101", 7709),
    ("青岛电信主站W1", "58.58.33.123", 7709),
    ("深圳电信主站Z1", "14.17.75.71", 7709),
    ("云行情上海电信Z1", "114.80.63.12", 7709),
    ("云行情上海电信Z2", "114.80.63.35", 7709),
    ("上海电信主站Z3", "180.153.39.51", 7709),
    ('招商证券深圳行情', '119.147.212.81', 7709),
    ('华泰证券(南京电信)', '221.231.141.60', 7709),
    ('华泰证券(上海电信)', '101.227.73.20', 7709),
    ('华泰证券(上海电信二)', '101.227.77.254', 7709),
    ('华泰证券(深圳电信)', '14.215.128.18', 7709),
    ('华泰证券(武汉电信)', '59.173.18.140', 7709),
    ('华泰证券(天津联通)', '60.28.23.80', 7709),
    ('华泰证券(沈阳联通)', '218.60.29.136', 7709),
    ('华泰证券(南京联通)', '122.192.35.44', 7709),
    ('华泰证券(南京联通)', '122.192.35.44', 7709),
    ('安信1', '112.95.140.74', 7709),
    ('安信2', '112.95.140.92', 7709),
    ('安信3', '112.95.140.93', 7709),
    ('安信4', '114.80.149.19', 7709),
    ('安信5', '114.80.149.21', 7709),
    ('安信6', '114.80.149.22', 7709),
    ('安信7', '114.80.149.91', 7709),
    ('安信8', '114.80.149.92', 7709),
    ('安信9', '121.14.104.60', 7709),
    ('安信10', '121.14.104.66', 7709),
    ('安信11', '123.126.133.13', 7709),
    ('安信12', '123.126.133.14', 7709),
    ('安信13', '123.126.133.21', 7709),
    ('安信14', '211.139.150.61', 7709),
    ('安信15', '59.36.5.11', 7709),
    ('广发1', '119.29.19.242', 7709),
    ('广发2', '123.138.29.107', 7709),
    ('广发3', '123.138.29.108', 7709),
    ('广发4', '124.232.142.29', 7709),
    ('广发5', '183.57.72.11', 7709),
    ('广发6', '183.57.72.12', 7709),
    ('广发7', '183.57.72.13', 7709),
    ('广发8', '183.57.72.15', 7709),
    ('广发9', '183.57.72.21', 7709),
    ('广发10', '183.57.72.22', 7709),
    ('广发11', '183.57.72.23', 7709),
    ('广发12', '183.57.72.24', 7709),
    ('广发13', '183.60.224.177', 7709),
    ('广发14', '183.60.224.178', 7709),
    ('国泰君安1', '113.105.92.100', 7709),
    ('国泰君安2', '113.105.92.101', 7709),
    ('国泰君安3', '113.105.92.102', 7709),
    ('国泰君安4', '113.105.92.103', 7709),
    ('国泰君安5', '113.105.92.104', 7709),
    ('国泰君安6', '113.105.92.99', 7709),
    ('国泰君安7', '117.34.114.13', 7709),
    ('国泰君安8', '117.34.114.14', 7709),
    ('国泰君安9', '117.34.114.15', 7709),
    ('国泰君安10', '117.34.114.16', 7709),
    ('国泰君安11', '117.34.114.17', 7709),
    ('国泰君安12', '117.34.114.18', 7709),
    ('国泰君安13', '117.34.114.20', 7709),
    ('国泰君安14', '117.34.114.27', 7709),
    ('国泰君安15', '117.34.114.30', 7709),
    ('国泰君安16', '117.34.114.31', 7709),
    ('国信1', '182.131.3.252', 7709),
    ('国信2', '183.60.224.11', 7709),
    ('国信3', '58.210.106.91', 7709),
    ('国信4', '58.63.254.216', 7709),
    ('国信5', '58.63.254.219', 7709),
    ('国信6', '58.63.254.247', 7709),
    ('海通1', '123.125.108.90', 7709),
    ('海通2', '175.6.5.153', 7709),
    ('海通3', '182.118.47.151', 7709),
    ('海通4', '182.131.3.245', 7709),
    ('海通5', '202.100.166.27', 7709),
    ('海通6', '222.161.249.156', 7709),
    ('海通7', '42.123.69.62', 7709),
    ('海通8', '58.63.254.191', 7709),
    ('海通9', '58.63.254.217', 7709),
    ('华林1', '120.55.172.97', 7709),
    ('华林2', '139.217.20.27', 7709),
    ('华林3', '202.100.166.21', 7709),
    ('华林4', '202.96.138.90', 7709),
    ('华林5', '218.106.92.182', 7709),
    ('华林6', '218.106.92.183', 7709),
    ('华林7', '220.178.55.71', 7709),
    ('华林8', '220.178.55.86', 7709),
]
TdxHq_hosts=[
('海通4', '182.131.3.245', 7709),
("上证云成都电信一", "218.6.170.47", 7709),
]

# 选择最快的行情主站
def select_fastest_host(hosts):
    fastest_host = None
    min_latency = float('inf')
    
    for name, ip, port in hosts:
        # 初始化TdxL2对象
        l2 = TdxHq_API()
        
        # 记录开始时间
        start_time = time.time()
        
        # 尝试连接行情服务器
        if l2.connect(ip, port):
            latency = time.time() - start_time
            print(f"port: {name} ({latency}:{min_latency})")
            if latency < min_latency:
                min_latency = latency
                fastest_host = (name, ip, port)
        
        # 关闭连接
        l2.disconnect()
    
    return fastest_host


def set_poll():
    ips = [(v[1], v[2]) for v in TdxHq_hosts]
    # 获取5个随机ip作为ip池
    random.shuffle(ips)
    ips5 = ips[:5]

    ## IP 池对象
    ippool = AvailableIPPool(TdxHq_API, ips5)

    ## 选出M, H
    primary_ip, hot_backup_ip = ippool.sync_get_top_n(2)
    print(f"set_poll: ({primary_ip}:{hot_backup_ip})")
    return hot_backup_ip
def get_stock_info_a_code_name():
    StockList=ak.stock_info_a_code_name()
    #StockList返回的股票代码是“000001”，“000002”这样的格式
    #但是stock_zh_a_daily（）函数中，要求代码的格式为“sz000001”，或“sh600001”
    #即必须有sz或者sh作为前序
    #因此，通过for循环对股票代码code进行格式变换
    for i in range(0,len(StockList)):
        temp=StockList.iloc[i,0]
        if temp[0]=="6":
            temp="sh"+temp
        if temp[0]=="0":
            temp="sz"+temp
        if temp[0]=="3":
            temp="sz"+temp
        StockList.iloc[i,0]=temp
    if os.path.exists("stockList.txt"):
           os.remove("stockList.txt")
    StockList.to_csv("stockList.txt",sep="\t",index=False,header=True)
    print(StockList)
def get_security_bars(primary_ip):    
    api=TdxHq_API()

    with api.connect(primary_ip[0], primary_ip[1]):
        data=[]
        for i in range(10):
            data+=api.get_security_bars(9,0,'000001',(9-i)*800,800)
    print(api.to_df(data))
def get_all_dat(primary_ip):    
    api=TdxHq_API()

    with api.connect(primary_ip[0], primary_ip[1]):
        ### 3. 获取股票列表
        if api.get_security_list():
            print(api.stock_count)  # 股票数量
            print(api.stocks)  # 股票代码列表

        ### 4. 获取股票实时行情
        #code = '000001'  # 股票代码
        # if api.get_market_data(code):
        #     print(api.get_market_data(code).code)  # 股票代码
        #     print(api.get_market_data(code).name)  # 股票名称
        #     print(api.get_market_data(code).price)  # 股票价格

        ### 5. 获取K线数据
        stocks = api.get_security_quotes([(0, "000001"), (1, "600300")])
        pprint.pprint(stocks)
        print("获取k线")
        data = api.get_security_bars(9, 0, '000001', 4, 3)
        pprint.pprint(data)
        print("获取 深市 股票数量")
        pprint.pprint(api.get_security_count(0))
        print("获取股票列表")
        stocks = api.get_security_list(1, 255)
        pprint.pprint(stocks)
        print("获取指数k线")
        data = api.get_index_bars(9, 1, '000001', 1, 2)
        pprint.pprint(data)
        print("查询分时行情")
        data = api.get_minute_time_data(TDXParams.MARKET_SH, '600300')
        pprint.pprint(data)
        print("查询历史分时行情")
        data = api.get_history_minute_time_data(
        TDXParams.MARKET_SH, '600300', 20161209)
        pprint.pprint(data)
        print("查询分时成交")
        data = api.get_transaction_data(TDXParams.MARKET_SZ, '000001', 0, 30)
        pprint.pprint(data)
        print("查询历史分时成交")
        data = api.get_history_transaction_data(
        TDXParams.MARKET_SZ, '000001', 0, 10, 20170209)
        pprint.pprint(data)
        print("查询公司信息目录")
        data = api.get_company_info_category(TDXParams.MARKET_SZ, '000001')
        pprint.pprint(data)
        print("读取公司信息-最新提示")
        data = api.get_company_info_content(0, '000001', '000001.txt', 0, 10)
        pprint.pprint(data)
        print("读取除权除息信息")
        data = api.get_xdxr_info(1, '600300')
        pprint.pprint(data)
        print("读取财务信息")
        data = api.get_finance_info(0, '000001')
        pprint.pprint(data)
        print("日线级别k线获取函数")
        data = api.get_k_data('000001', '2017-07-01', '2017-07-10')
        pprint.pprint(data)
    

if __name__ == '__main__':
    #get_stock_info_a_code_name()
    primary_ip=set_poll()
    #get_security_bars(primary_ip)
    get_all_dat(primary_ip)
     
    